package cn.stazxr.dbutils;

import cn.stazxr.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.junit.Assert;
import org.junit.Test;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author talentestors
 * @version 1.0
 * @since 2025.05.24
 **/
@SuppressWarnings("all")
public class UtilTest {

	private final QueryRunner runner = new QueryRunner(PoolUtil.getDatasource());

	@Test
	public void testJoin() {
		record TeacherAndUser(int tid, String tname, int sid, String sname, String spassword) {
		}
		try {
			ResultSetHandler<List<TeacherAndUser>> h = (rs -> {
				List<TeacherAndUser> users = new ArrayList<>();
				while (rs.next()) {
					TeacherAndUser user = new TeacherAndUser(
							rs.getInt("tid"),
							rs.getString("tname"),
							rs.getInt("sid"),
							rs.getString("sname"),
							rs.getString("spassword")
					);
					users.add(user);
				}
				return users;
			});
			List<TeacherAndUser> result = runner.query("""
					SELECT
					  t.id tid,
					  t.`name` tname,
					  s.id sid,
					  s.username sname,
					  s.`password` spassword
					FROM
					  teacher t
					  LEFT JOIN `user` s ON t.id = s.t_id	
					""", h);
			System.out.println("testJoin: ");
			for (TeacherAndUser user : result) {
				System.out.println(user);
			}
		} catch (SQLException e) {
			Assert.fail(e.getMessage());
		}
	}

	@Test
	public void testSelect() {
		ResultSetHandler<User> h = new BeanHandler<User>(User.class);
		try {
			User user = runner.query("select * from user where id = ?", 1, h);
			System.out.println(user);
		} catch (SQLException e) {
			Assert.fail(e.getMessage());
		}
	}

	@Test
	public void testSelect2() {
		ResultSetHandler<List<User>> h = new ResultSetHandler<List<User>>() {
			@Override
			public List<User> handle(ResultSet resultSet) throws SQLException {
				List<User> users = new ArrayList<>();
				while (resultSet.next()) {
					User user = new User();
					user.setId(resultSet.getInt("id"));
					user.setUsername(resultSet.getString("username"));
					user.setPassword(resultSet.getString("password"));
					users.add(user);
				}
				return users;
			}
		};
		try {
			List<User> users = runner.query("select * from user", h);
			System.out.println("select2: ");
			for (User user : users) {
				System.out.println(user);
			}
		} catch (SQLException e) {
			Assert.fail(e.getMessage());
		}
	}

	@Test
	public void testUpdate() {
		try {
			int rows = runner.update("update user set username = ?, password = ? where id = ?", "stazxr", "1233333", 1);
			System.out.println(rows);
		} catch (SQLException e) {
			Assert.fail(e.getMessage());
		}
	}

}
